<script lang="ts" setup>
import type { VbenFormSchema } from '#/adapter/form';

import { computed, ref } from 'vue';

import { useVbenDrawer } from '@vben/common-ui';

import { breakpointsTailwind, useBreakpoints } from '@vueuse/core';
import dayjs from 'dayjs';

import { useVbenForm, z } from '#/adapter/form';
import {
  createTender,
  getCompanies,
  getRegionTree,
  getTags,
  getTenderTypes,
  updateTender,
} from '#/api';

interface TenderFormData {
  [key: string]: any;
  /** 后端权限标识 */
  title?: string;
  region_id?: number;
}

const emit = defineEmits<{
  success: [];
}>();
const formData = ref<TenderFormData>();
const schema: VbenFormSchema[] = [
  {
    component: 'Input',
    fieldName: 'title',
    label: '标题',
    formItemClass: 'col-span-2 md:col-span-2',
    rules: z.string().min(2, `至少2个字符`),
  },
  {
    component: 'DatePicker',
    fieldName: 'publish_date',
    label: '发布时间',
    rules: 'required',
  },
  {
    component: 'ApiTreeSelect',
    componentProps: {
      api: () => getRegionTree(),
      class: 'w-full',
      filterable: true,
      labelField: 'name',
      valueField: 'id',
      childrenField: 'children',
    },
    fieldName: 'region_id',
    label: '区域',
    rules: 'required',
  },
  {
    component: 'ApiSelect',
    componentProps: {
      api: () => getTenderTypes(),
      labelField: 'name',
      valueField: 'id',
    },
    fieldName: 'type_id',
    label: '招标状态',
    rules: 'required',
  },
  {
    component: 'ApiSelect',
    componentProps: {
      api: () => getTags('project_type'),
      labelField: 'name',
      valueField: 'id',
      multiple: true,
    },
    fieldName: 'tag.project_type',
    label: '项目类型',
    rules: 'required',
  },
  {
    component: 'Input',
    fieldName: 'url',
    formItemClass: 'col-span-2 md:col-span-2',
    label: '来源网址',
  },
  {
    component: 'ApiSelect',
    componentProps: {
      api: () => getTags('project'),
      labelField: 'name',
      valueField: 'id',
      multiple: true,
    },
    fieldName: 'tag.project',
    label: '标签',
  },
  {
    component: 'ApiSelect',
    componentProps: {
      api: () => getCompanies(),
      labelField: 'name',
      valueField: 'id',
      filterable: true,
    },
    fieldName: 'entity_id',
    label: '采购单位',
  },
  {
    component: 'ApiSelect',
    componentProps: {
      api: () => getCompanies(),
      labelField: 'name',
      valueField: 'id',
      filterable: true,
    },
    fieldName: 'agent_id',
    label: '招标代理',
  },
  {
    component: 'Textarea',
    fieldName: 'summary',
    label: '项目概况',
    formItemClass: 'col-span-2 md:col-span-2',
  },
  {
    component: 'RangePicker',
    componentProps: {
      cancelRangeSelectLimit: true,
    },
    defaultValue: [dayjs().subtract(7, 'days'), dayjs()],
    fieldName: 'publish_date2',
    label: '发布时间',
    formItemClass: 'col-span-2 md:col-span-2',
  },
  {
    component: 'Textarea',
    fieldName: 'content',
    label: '公告内容',
    formItemClass: 'col-span-2 md:col-span-2',
  },
];

const breakpoints = useBreakpoints(breakpointsTailwind);
const isHorizontal = computed(() => breakpoints.greaterOrEqual('md').value);

const [Form, formApi] = useVbenForm({
  commonConfig: {
    colon: true,
    formItemClass: 'col-span-2 md:col-span-1',
  },
  schema,
  showDefaultActions: false,
  wrapperClass: 'grid-cols-2 gap-x-4',
});

const [Drawer, drawerApi] = useVbenDrawer({
  onConfirm: onSubmit,
  onOpenChange(isOpen) {
    if (isOpen) {
      const data = drawerApi.getData<TenderFormData>();
      if (data) {
        formData.value = data;
        formApi.setValues(formData.value);
      } else {
        formApi.resetForm();
      }
    }
  },
});

async function onSubmit() {
  const { valid } = await formApi.validate();
  if (valid) {
    drawerApi.lock();
    const data = await formApi.getValues<TenderFormData>();
    try {
      await (formData.value?.id
        ? updateTender(formData.value.id, data)
        : createTender(data));
      drawerApi.close();
      emit('success');
    } finally {
      drawerApi.unlock();
    }
  }
}
const getDrawerTitle = computed(() =>
  formData.value?.id ? '修改招标信息' : '添加招标信息',
);
</script>
<template>
  <Drawer class="w-full max-w-[800px]" :title="getDrawerTitle">
    <Form class="mx-4" :layout="isHorizontal ? 'horizontal' : 'vertical'" />
  </Drawer>
</template>
